package com.cms.work.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

/**
 * <p>Title: ResourceCheckFilter</p>
 * <p>Description: 权限资源检查过滤器</p>
 * <p>Email: yuyue_qty@163.com</p>
 * @author 晴天雨
 * @date 2016年2月2日下午5:16:12
 * @version 1.0
 */
public class ResourceCheckFilter extends AccessControlFilter {
	
	private static final Logger logger = Logger.getLogger(ResourceCheckFilter.class);

	//无权访问时返回地址
	private String errUrl;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		String url = getPathWithinApplication(request);
		HttpServletRequest hrt = (HttpServletRequest) request;
		//获取Url后面的.action字符串
		if(url.contains(".")){
			url = url.substring(0, url.indexOf("."));
		}
		boolean isPermitted = subject.isPermitted(url);
		if(!isPermitted){
			hrt.getSession().setAttribute("msg", "权限不足");
		}
		logger.info(url + "  " + isPermitted);
		return isPermitted;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest hrt = (HttpServletRequest) request;
		HttpServletResponse hpe = (HttpServletResponse) response;
		hpe.sendRedirect(hrt.getContextPath() + "/" + errUrl);
		return false;
	}
	
	public String getErrUrl() {
		return errUrl;
	}
	public void setErrUrl(String errUrl) {
		this.errUrl = errUrl;
	}

}
